﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Data;
using System.Linq;
using Microsoft.Phone.Controls;
namespace Phone.Framework.Behaviors
{

    public class MenuContextBehavior : Behavior<ContextMenu>
    {
    
        protected override void OnAttached()
        {
            AssociatedObject.Loaded += new RoutedEventHandler(menu_Element_Loaded);
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
          
            base.OnDetaching();
        }


        public string ElementName { get; set; }

        private void menu_Element_Loaded(object sender, RoutedEventArgs e)
        {
            var menu = sender as ContextMenu;

            if (menu != null)
            {
                if (menu.Owner != null)
                {
                    var ee = menu.Owner as FrameworkElement;
                    ee.SetBinding(FrameworkElement.TagProperty, new Binding("DataContext") { ElementName = this.ElementName });
                    if(ee.Tag!=null)
                    Caliburn.Micro.Action.SetTargetWithoutContext(menu, ee.Tag);
                    //  MessageBox.Show(ee.Tag.ToString());
                }
            }
            AssociatedObject.Loaded -= new RoutedEventHandler(menu_Element_Loaded);
        }
    }
}
